<template>
  <div ref="imgTooles">
    <div v-if="uploadtype == 'uploadImg'">
      <a-upload
        :key="uploadKey"
        list-type="picture-card"
        accept="image/*"
        :customRequest="uploadFile"
        @change="handleChange"
        @preview="handlePreview"
        :before-upload="(file) => beforeUpload(file)"
        :file-list="fileList"
        :disabled="disabled"
      >
        <!-- 图片样式上传 -->
        <div v-if="!disabled && fileList.length < maxFile">
          <a-icon type="plus" />
          <div class="ant-upload-text">{{ label }}</div>
        </div>
      </a-upload>
      <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
    </div>
    <a-upload
      :accept="FILETYPE"
      v-else-if="uploadtype == 'uploadFile'"
      :customRequest="uploadFile"
      @change="handleChange"
      @preview="fileView"
      :before-upload="(file) => beforeUpload(file)"
      :file-list="fileList"
      name="file"
      :multiple="true"
      :disabled="disabled"
    >
      <div v-if="!disabled && fileList.length < maxFile">
        <a-button> <a-icon type="upload" /> {{ label }} </a-button>
      </div>
    </a-upload>
  </div>
</template>

<script>
import { minioUpload, getFile } from '@/api/base/file.js'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
import { getFileSize } from '@/utils/util.js'
import { FILESIZE, FILETYPE } from '../../store/mutation-types.js'
export default {
  props: {
    field: {
      type: String,
    },
    value: {},
    // 上传控件类型 uploadFile | uploadImg
    uploadtype: {
      type: String,
      default: 'uploadFile'
    },
    label: {
      type: String,
    },
    // 标记,
    sign: {
      type: [Number, String],
      default: 1,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    maxFile: {
      type: Number,
      default: 10,
    },
    // 循环组件下标
    index: {
      type: Number
    }
  },
  data() {
    return {
      FILETYPE: FILETYPE,
      uploadKey: 0,
      previewVisible: false,
      previewImage: '',
      fileList: [], // 文件列表
      loading: false, // 上传状态
    }
  },
  watch: {
    value(val) {
      if (this.fileList.length == 0) {
        // console.log('回显', this.fileList)
        if (val && val.length > 0) {
          this.getFileData(val)
        }
      } else if (val) {
        // 厂区图片处理
        this.fileList = []
        this.getFileData(val)
      }
    },
  },
  created() {
    // console.log('附件回显', this.value)
    if (this.value && this.value.length > 0) {
      this.getFileData(this.value)
    } else {
      this.fileList = []
      this.uploadKey++
    }
  },
  methods: {
    // 图片预览
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancel() {
      this.previewVisible = false
    },
    // 附件在线预览
    fileView(file) {
      console.log('文件预览', file)
      window.open(file.url)
    },
    // 附件回显
    getFileData(ids) {
      let idArr = ids.split(',')
      idArr.forEach((v) => {
        getFile({ id: v }).then((res) => {
          // console.log('附件回显', res)
          if (res.data == null) {
            console.warn('无效附件id', v)
          } else {
            let file = {
              uid: res.data.id,
              name: res.data.name,
              status: 'done',
              url: res.data.url,
            }
            this.fileList.push(file)
          }
        })
      })
    },
    // 回显父组件数据 / 重置表单校验
    updateDataF(fileData) {
      let ids = fileData.map((v) => {
        return v.uid
      })
      console.log('更新id', ids, typeof ids.join(','))
      // 文件id以逗号分隔
      this.$emit('updatedValueF', ids.join(','), this.field, this.sign, this.index)
      // 重新触发一次校验
      this.$emit('f_updateCheck', this.field, this.sign, this.index)
    },
    // 文件上传前
    beforeUpload(file) {
      // console.log('上传前类型', this.accept, file)
      // 校验文件大小
      return new Promise(async (resolve, reject) => {
        // console.log('file.type', file.type)
        let fileSize = getFileSize(file.size)
        if (Number(fileSize) > FILESIZE) {
          this.$message.warning(`文件大小不能超过${FILESIZE}M`)
          return reject()
        } else {
          return resolve()
        }
      })
    },
    // 文件上传
    uploadFile(data) {
      // 上传文件
      this.loading = true
      minioUpload(data.file).then((res) => {
        // console.log('上传文件', res, data)
        if (res.code == 0) {
          data.onSuccess()
          // console.log('this.fileList', this.fileList)
          this.fileList[this.fileList.length - 1]['uid'] = res.data.id
          this.fileList[this.fileList.length - 1]['url'] = res.data.url
        }
        this.loading = false
        this.updateDataF(this.fileList || [])
        // console.log('上传后', this.fileList)
      })
    },
    // 图片上传前校验
    handleChange({ fileList }) {
      // 附件加减触发
      this.$emit('changer')
      this.fileList = fileList
      if (!this.loading) {
        this.updateDataF(this.fileList || [])
      }
    },
  },
}
</script>

<style scoped>
</style>